//
//  GroupDetailViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-15.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupDetailViewController.h"
#import "User.h"
#import "GuaziAppDelegate.h"
#import "PostView.h"
#import "MessagePicker.h"
#import "GroupUserListViewController.h"
#import "GroupAddViewController.h"
#import "ContactsViewController.h"
#import "FriendGroup.h"

@interface GroupDetailViewController(private)
- (void) buildToolbar;
@end



@implementation GroupDetailViewController

@synthesize group;
@synthesize nameLabel;
@synthesize accessLabel;
@synthesize countLabel;

#pragma mark -
#pragma mark Initialization


- (id) initWithGroup:(FriendGroup*)g
{
    self = [super init];
	if ( self ) {
		self.group = g;
	}
	return self;
}


#pragma mark -
#pragma mark View lifecycle


- (void) loadView
{
	self.view = [[[NSBundle mainBundle] loadNibNamed:@"GroupDetailView" owner:self options:nil] lastObject];
	self.navigationItem.title = group.name;
	[self buildToolbar];
}



- (void)viewWillAppear:(BOOL)animated 
{
	self.nameLabel.text = group.name;
	self.accessLabel.text = group.isPublic ? @"公开" : @"私秘";
	self.countLabel.text = [NSString stringWithFormat:@"%d", group.friendCount];
	[super viewWillAppear:animated];
}
 

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


- (void) buildToolbar
{
	if ( toolbar ) {
		[toolbar release];
		toolbar = nil;
	}
	
	toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 376, 320, 40)];
	NSMutableArray* toolbarItems = [NSMutableArray array];
	
	if ( [group.friends count] > 0 ) {
		BOOL canTwitter = NO;
		BOOL canDM = NO;
		BOOL canMessage = NO;
		
		for ( User* user in group.friends ) {
			if ( user.contact && user.phone && [user.phone length]>0 ) {
				canMessage = YES;
			}
			if ( user.userId > 0 ) {
				canTwitter = YES;
				if ( [user.relation compare:kUserRelationBoth] == NSOrderedSame ) {
					canDM = YES;
				}
			}
		}
		
		//发动态
		if ( canTwitter ) {
			UIBarButtonItem* button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose 
																					 target:self action:@selector(postTweet)] autorelease];
			[toolbarItems addObject:button];
		}
		
		//发私信
		if ( canDM ) {
			UIBarButtonItem* button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose 
																					 target:self action:@selector(postDirectMessage)] autorelease];
			[toolbarItems addObject:button];
		}
		
		//发短信
		if ( canMessage ) {
			UIBarButtonItem* button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply 
																					 target:self action:@selector(sendMessage)] autorelease];
			[toolbarItems addObject:button];
		}
		
		//编辑
		UIBarButtonItem* button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks 
																				 target:self action:@selector(editGroup)] autorelease];
		[toolbarItems addObject:button];
	}

	//组内成员
	UIBarButtonItem* button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
																			 target:self action:@selector(member)] autorelease];
	[toolbarItems addObject:button];

	//删除
	button = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash 
																			target:self action:@selector(deleteGroup)] autorelease];
	[toolbarItems addObject:button];
	NSMutableArray* arr = [NSMutableArray arrayWithCapacity:2*[toolbarItems count]-1];
	UIBarButtonItem* item = nil;
	UIBarButtonItem* space = nil;
	
	for ( int i=0; i<[toolbarItems count]; i++ ) {
		item = [toolbarItems objectAtIndex:i];
		[arr addObject:item];
		if ( i != [toolbarItems count] - 1 ) {
			space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace 
																   target:self action:nil] autorelease];
			[arr addObject:space];
		}
	}
	
	[toolbar setItems:arr animated:YES];
	[self.view addSubview:toolbar];
}


//发动态
- (void) postTweet
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView postGroup:group];
}


//fa私信
- (void)postDirectMessage
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView editDirectMessageGroup:group];
}


//发短信
- (void) sendMessage
{
	NSMutableArray* array = [NSMutableArray array];;
	for ( User* user in group.friends ) {
		if ( user.phone != nil && [user.phone length] > 0 ) {
			[array addObject:user.phone];
		}
	}
	
	if ( [array count] > 0 ) {
		MessagePicker* picker = [[MessagePicker alloc] initWithController:self recienpts:array body:@""];
		[picker send];
		[picker release];
	}
}


//编辑组
- (void) editGroup
{
	GroupAddViewController* controller = [[GroupAddViewController alloc] init];
	controller.group = group;
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


//组内成员
- (void) member
{
	GroupUserListViewController* controller = [[GroupUserListViewController alloc] initWithGroup:group];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


//删除组
- (void) deleteGroup
{
	UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"删除组后，本组内的联系人将变成未分组状态。是否确认删除本组？" 
													   delegate:self 
											  cancelButtonTitle:@"取消" 
										 destructiveButtonTitle:@"确认" otherButtonTitles:nil];
	[sheet showInView:self.view];
	[sheet release];
}


- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if ( buttonIndex == 0 ) {
		[TwitterClient destroyUserGroupSync:group.groupId];
		[self.navigationController popViewControllerAnimated:YES];
		
		UINavigationController* nav = [[GuaziAppDelegate getAppDelegate].tabBarController.viewControllers objectAtIndex:0];
		UIViewController* c = nav.topViewController;
		if ( c && [c isKindOfClass:[ContactsViewController class]]) {
			ContactsViewController* v = (ContactsViewController*)c;
			FriendGroup* fg = nil;
			for ( FriendGroup* g in v.groups ) {
				if ( g.groupId == group.groupId ) {
					fg = g;
					break;
				}
			}
			
			if ( fg ) {
				[v.groups removeObject:fg];
				[v.tableView reloadData];
			}
		}
	}
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	self.group = nil;
	self.nameLabel = nil;
	self.accessLabel = nil;
	self.countLabel = nil;
	[toolbar release];
}


- (void)dealloc {
	[group release];
	[nameLabel release];
	[accessLabel release];
	[countLabel release];
	[toolbar release];
    [super dealloc];
}


@end

